package com.aimei.core.moduel.util;

import com.aimei.www.modules.exception.ExceptionBase;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xiah
 * @date 2018/5/2 17:10
 */
public class JwtToken {
       private static final String SECRITY = UUID.randomUUID().toString();

       /**
        * @author xiah
        * description:生产临时token
        * param:
        * return:
        * date: 2018/5/2
        */
       public static String createToken() throws Exception {
              Map map = new HashMap();
              Date date = new Date();
              map.put("typ", "JWT");
              map.put("alg", "HS256");
              String token = JWT.create().withHeader(map).withClaim("company", "cp58").withIssuer("xiah").withIssuedAt
                      (date)
                      .withExpiresAt(new Date(date.getTime() + 1000 * 60 * 10))
                      .sign(Algorithm.HMAC256(SECRITY));
              return token;
       }

       /**
        * @author xiah
        * description: 生产刷新token，有效时间一个月
        * param:
        * return:
        * date: 2018/5/2
        */
       public static String createPermanentToken() throws Exception {
              Map map = new HashMap();
              Date date = new Date();
              map.put("typ", "JWT");
              map.put("alg", "HS256");
              String token = JWT.create().withHeader(map).withClaim("company", "cp58").withIssuer("xiah").withIssuedAt
                      (date)
                      .withExpiresAt(new Date(date.getTime() + 1000 * 60 * 60 * 24 * 30 * 12))
                      .sign(Algorithm.HMAC256(SECRITY));
              return token;
       }

       /**
        * @author xiah
        * description:
        * param:
        * return:
        * date: 2018/5/3
        */
       public static Map creatTokenMap() throws Exception {
              Map map = new HashMap();
              map.put("token", createToken());
              map.put("refresh_token", createPermanentToken());
              return map;
       }

       /**
        * @author xiah
        * description: 验证token的正确性
        * param:
        * return:
        * date: 2018/5/2
        */
       public static Boolean checkToken(String token) throws Exception {
              JWTVerifier verification = JWT.require(Algorithm.HMAC256(SECRITY)).build();
              try {
                     verification.verify(token);
                     return true;
              } catch ( Exception e ) {
                     e.hashCode();
                     throw new ExceptionBase(122, "token is wrong");
              }
       }
}
